package com.ptszyxx.popose.module.main.mine;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.alipay.sdk.app.PayTask;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ysg.base.BaseActivity;
import com.ysg.enums.PayEnum;
import com.ysg.http.data.AppViewModelFactory;
import com.ptszyxx.popose.databinding.FragmentMineRechargeBinding;
import com.ptszyxx.popose.module.main.mine.adapter.MineRechargeAdapter;
import com.ysg.http.data.entity.mine.MineDiamondEntity;
import com.ptszyxx.popose.module.main.mine.vm.MineRechargeVM;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YConfigUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.PayDialog;
import java.util.List;
import java.util.Map;

/**
 * 钻石充值
 */
public class MineRechargeFragment extends BaseActivity<FragmentMineRechargeBinding, MineRechargeVM> {
    private MineRechargeAdapter adapter;

    public static MineRechargeFragment getInstance() {
        return new MineRechargeFragment();
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.fragment_mine_recharge;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MineRechargeVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MineRechargeVM.class);
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.requestDiamond();
    }

    @Override
    public void initAdapter() {
        adapter = new MineRechargeAdapter();
        YRecyclerViewUtil.initNoLine(this, binding.recyclerView, adapter);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, o -> setAdapterData((List<MineDiamondEntity>)o));
        viewModel.uc.onPayDialogEvent.observe(this, o -> showDialogPay());
        viewModel.uc.onAlipayEvent.observe(this, o -> startAlipay());
    }

    private void setAdapterData(List<MineDiamondEntity> list) {
        adapter.setList(list);
    }

    private void showDialogPay() {
        if (!viewModel.privacyChecked.get()){
            YToastUtil.showShort(R.string.recharge_agreement_check_tip);
            return;
        }

        List<MineDiamondEntity> list = adapter.getData();
        if(YCollectionUtil.isEmpty(list)){
            return;
        }
        boolean flag = true;
        MineDiamondEntity diamondEntity = null;
        for (MineDiamondEntity item: list) {
            if (item.isChecked()){
                flag = false;
                diamondEntity = item;
                break;
            }
        }
        if (flag){
            YToastUtil.showShort(R.string.mine_recharge_diamond_tip);
            return;
        }

        MineDiamondEntity finalDiamondEntity = diamondEntity;
        YDialogUtil.getInstance().showPay(this, diamondEntity.getMoney())
                .setOnPayListener(new PayDialog.OnPayListener() {

                    @Override
                    public void onPay(PayEnum payEnum) {
                        if (PayEnum.wechat == payEnum){
                            viewModel.requestPay("2", finalDiamondEntity.getId());
                        }else{
                            if (YConfigUtil.getPayApp()){
                                viewModel.requestPayApp("1", finalDiamondEntity.getId());
                            }else{
                                viewModel.requestPay("1", finalDiamondEntity.getId());
                            }
                        }
                    }
                });
    }

    private Runnable payRunnable = new Runnable() {
        @Override
        public void run() {
            PayTask alipay = new PayTask(MineRechargeFragment.this);
            Map<String,String> result = alipay.payV2(viewModel.orderInfo,true);
            Message msg = new Message();
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    // 必须异步调用
    private void startAlipay(){
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultStatus = payResult.getResultStatus();
            if (TextUtils.equals(resultStatus, "9000")) {
                YToastUtil.showShort("支付成功");
            } else {
                YToastUtil.showShort("支付失败");
            }
        }
    };

}
